package main

import (
	"flag"
	"fmt"
	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest"
	"listenboos-common/tools"
	"net/http"
	"ucenter-api/internal/config"
	"ucenter-api/internal/handler"
	"ucenter-api/internal/svc"
)

var configFile = flag.String("f", "etc/conf.yaml", "the config file")

func main() {
	flag.Parse()
	// 替换打印日志
	logx.MustSetup(logx.LogConf{Stat: false, Encoding: "plain"})
	var c config.Config
	conf.MustLoad(*configFile, &c)

	server := rest.MustNewServer(c.RestConf, rest.WithCors())
	//rest.WithCustomCors(
	//func(header http.Header) {
	//	//header.Set("Access-Control-Allow-Headers", "DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,token,x-auth-token") }
	//nil, func(writer http.ResponseWriter) {
	//	writer.Header().Set("Access-Control-Allow-Origin", "*")
	//	writer.Header().Set("Access-Control-Allow-Headers", "*")
	//	writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH")
	//	writer.Header().Set("Access-Control-Expose-Headers", "Content-Length, Content-Type, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
	//	writer.Header().Set("Access-Control-Allow-Credentials", "true")
	//}, "*"))
	defer server.Stop()
	server.Use(tools.NewCorsMiddleware().Handle)
	//server := rest.MustNewServer(c.RestConf, rest.WithUnauthorizedCallback(func(w http.ResponseWriter, r *http.Request, err error) {
	//	httpx.Error(w, err)
	//}), rest.WithCors("*"))
	//defer server.Stop()
	//	server.Use(CorsMiddleware)
	ctx := svc.NewServiceContext(c)
	router := handler.NewRouters(server)
	handler.RegisterHandlers(router, ctx)

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}

func CorsMiddleware(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		//指定允许其他域名访问
		//ctx.Writer.Header().Set("Access-Control-Allow-Origin", "http://localhost:8080")
		w.Header().Set("Access-Control-Allow-Origin", "*") //跨域：CORS(跨来源资源共享)策略
		//预检结果缓存时间
		w.Header().Set("Access-Control-Max-Age", "86400")
		//允许的请求类型（GET,POST等）
		w.Header().Set("Access-Control-Allow-Methods", "*")
		//允许的请求头字段
		w.Header().Set("Access-Control-Allow-Headers", "*")
		//是否允许后续请求携带认证信息（cookies）,该值只能是true,否则不返回
		w.Header().Set("Access-Control-Allow-Credentials", "true")
		if r.Method == http.MethodOptions {
			w.WriteHeader(http.StatusOK)
			return
		}
		next(w, r)
	}
}
